import axios from 'axios'
import { useUserStore } from '@/stores/user'
import router from '@/router'

// 创建axios实例
const service = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: 1000000
})

// 请求拦截器：自动携带Token
service.interceptors.request.use(
  (config) => {
    const userStore = useUserStore()
    
    // 排除登录接口
    if (!config.url.includes('/login/*')) {
      console.log(userStore)
      if (userStore.token) {
        config.headers.Authorization = `Bearer ${userStore.token}`
      } else {
        // router.push('/login?redirect=${encodeURIComponent(router.currentRoute.value.fullPath)}')
        // return Promise.reject(new Error('未授权'))
       
      }
    }
    
    // 可选：添加设备指纹等通用参数
    config.headers['X-Client-Id'] = localStorage.getItem('client_id') || ''
    
    return config
  },
  (error) => {
    // return Promise.reject(error)
  }
)

// 响应拦截器：统一处理401错误
service.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    // if (error.response?.status === 401) {
    //   const userStore = useUserStore()
    //   userStore.logout()
      
    // }
    
    // // 处理其他错误状态码
    // const message = error.response?.data?.message || error.message
    // return Promise.reject(message)
  }
)

export default service